package com.open.thinks.todo.system.dao.impl;

import java.io.Serializable;

import org.neodatis.odb.ODB;
import org.neodatis.odb.OID;
import org.neodatis.odb.Objects;
import org.neodatis.odb.Values;
import org.neodatis.odb.core.query.IQuery;
import org.neodatis.odb.core.query.IValuesQuery;

import com.open.thinks.todo.system.dao.OpenDao;

public class OpenNoSQLDao implements OpenDao {

	ODBProvider oddPprovider;

	@Override
	public void persist(Object o) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			session.store(o);
		} finally {
			if (session != null)
				session.commit();
		}
	}

	@Override
	public void merge(Object o) {

	}

	@Override
	public void remove(Object o) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			session.delete(o);
		} finally {
			if (session != null)
				session.commit();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T load(Class<T> clazz, Serializable id) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			return (T) session.getObjectFromId((OID) id);
		} finally {
			//			if (session != null)
			//				session.commit();
		}
	}

	public void removeAll(Object o) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			session.deleteCascade(o);
		} finally {
			if (session != null)
				session.commit();
		}
	}

	public <T> Objects<T> queryObjects(IQuery query, int... range) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			if (range == null || range.length < 2)
				return session.getObjects(query);
			else
				return session.getObjects(query, false, range[0], range[1]);
		} finally {
			//			if (session != null)
			//				session.commit();
		}
	}

	public <T> Objects<T> queryObjects(Class<T> clazz, int... range) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			if (range == null || range.length < 2)
				return session.getObjects(clazz);
			else
				return session.getObjects(clazz, false, range[0], range[1]);
		} finally {
			//			if (session != null)
			//				session.commit();
		}
	}

	public Values queryValues(IValuesQuery query) {
		ODB session = null;
		try {
			session = oddPprovider.getODB();
			return session.getValues(query);
		} finally {
			//			if (session != null)
			//				session.commit();
		}
	}
}
